package cn.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.dao.MessageDAO;
import cn.model.Message;
import cn.model.Users;


@WebServlet("/message/manager")
public class MessageManagerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String func = request.getParameter("func");
		Users loginUser=(Users)request.getSession().getAttribute("loginUser");
		if(loginUser==null) {
			request.getRequestDispatcher("/user/login.jsp").forward(request, response);
			return;
		}

		if ("add".equals(func)) 
			add(request, response);
		else if ("delete".equals(func))
			delete(request, response);
		else show(request, response);

	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		Users loginUser=(Users)request.getSession().getAttribute("loginUser");
		Message obj = new Message();
		obj.setTitle(title);
		obj.setContent(content);
		obj.setName(loginUser.getUsername());
		MessageDAO messageDao = new MessageDAO();
	   	messageDao.insert(obj);
		show(request, response);
	}
	private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		new MessageDAO().delete(Integer.parseInt(id));
		show(request, response);
	} 
	
	private void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MessageDAO messageDao = new MessageDAO();
		List<Message> list= messageDao.getAll();
		request.setAttribute("list", list);
		request.getRequestDispatcher("/showMessages.jsp").forward(request, response);
	}
}

	

